<template>
  <view class="base-select">
    <view class="base-select__select">
      <view class="base-select__select--label" @click="show">
        <text v-if="selected && selected[props.defaultProps.label]" :style="props.labelStyle">{{
          selected[props.defaultProps.label]
        }}</text>
        <text v-else :style="props.placeholderStyle">{{ props.title }}</text>
      </view>
      <template v-if="props.showIcon">
        <view class="base-select__icon" @click.stop="handleSelect(null)">
          <uv-icon name="close-circle-fill" v-if="selected" size="14"></uv-icon>
        </view>
        <view class="base-select__icon" @click="show">
          <uv-icon name="arrow-down" size="12"></uv-icon>
        </view>
      </template>
    </view>
    <base-popup ref="popupRef" round mode="bottom">
      <view class="base-select__popup">
        <view class="base-select__title">{{ props.title }}</view>
        <base-tree
          :value="props.value"
          @select="handleSelect"
          :treeData="props.option"
          :defaultProps="props.defaultProps"
        />
      </view>
    </base-popup>
  </view>
</template>

<script setup>
import BasePopup from "@/components/base-popup/uv-popup.vue";
import BaseTree from "@/components/base-tree/index.vue";

const emits = defineEmits(["select"]);

const props = defineProps({
  value: {
    type: [String, Number, Object],
    default: "",
  },
  option: {
    type: Array,
    default: () => [],
  },
  title: {
    type: String,
    default: "请选择",
  },
  defaultProps: {
    type: Object,
    default: () => ({
      label: "label",
      value: "value",
      children: "children",
    }),
  },
  showIcon: {
    type: Boolean,
    default: true,
  },
  labelStyle: {
    type: String,
    default: "",
  },
  placeholderStyle: {
    type: String,
    default: "",
  },
});

const popupRef = ref(null);
const selected = ref(null);

const show = () => popupRef.value.open();
const handleSelect = (item) => {
  selected.value = item;
  emits("select", item);
  popupRef.value.close();
};

watch(
  () => props.value,
  (val) => {
    selected.value = val;
  },
  { immediate: true }
);

defineExpose({ show });
</script>

<style lang="scss">
.base-select {
  &__select {
    font-size: 12px;
    margin-bottom: 4px;
    display: flex;
    align-items: center;

    &--label {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .label-icon {
        margin-left: 4px;
      }
    }
  }

  &__icon {
    margin-left: 4px;
  }

  &__popup {
    padding: 12px;
    height: 300px;
    overflow-y: auto;
  }

  &__title {
    font-size: 14px;
    text-align: center;
  }
}
</style>
